<?php
namespace app\web\controller;

use app\model\Util; 
use app\model\Ad; 
use app\model\Theme; 

class Mbxx extends Base
{
    public function Mbxx()
    {
global $_G, $_P;
$system = $_G['system'];
//load_func('tpl');
$GLOBALS['frames'] = array();
$themeid = intval($_P['themeid']);
if($themeid <= 0){
    $themeid = Theme::getDefaultThemenew();
}
$theme = Theme::getThemeById($themeid);
$config =   Theme::getConfig($themeid);
if(empty($themeid)){
    return_msg('还没有创建活动,请联系管理员');
}
$op = trim($_P['op']);
$do = 'record';

$mblist = Ad::getMbList($system,$config,$themeid);

if ($op=='post' || $op=='confirm'){
    foreach ($mblist as $item){
        if ($item['template_id']==$_P['template_id']){
            $mbinfo = $item;
        }
    }
    $title = mb_substr($theme['title'],0,20,'utf-8');
    $jubf = mb_substr($theme['jubf'],0,20,'utf-8');
    $add = $config['city'] .$config['district'] .$config['addresstxt'];
    $address = mb_substr($add,0,20,'utf-8');
    $form=[];
    if ($mbinfo['name']=="预约到店提醒"){
        $form[]=array(
            'name'=>'门店',
            'value'=>$jubf,
            'key'=>'thing1',
        );
        $form[]=array(
            'name'=>'地址',
            'value'=>$address,
            'key'=>'thing2',
        );
        $form[]=array(
            'name'=>'到店时间',
            'type'=>'daterange',
            'key'=>'time3',
        );
        $form[]=array(
            'name'=>'温馨提示',
            'type'=>'',
            'key'=>'thing4',
        );
    }
    if ($mbinfo['name']=="活动进度提醒"){
        $form[]=array(
            'name'=>'活动名称',
            'value'=>$title,
            'key'=>'thing1',
        );
        $form[]=array(
            'name'=>'活动时间',
            'type'=>'daterange',
            'key'=>'time2',
        );
        $form[]=array(
            'name'=>'活动进度',
            'value'=>'',
            'key'=>'thing3',
        );
        $form[]=array(
            'name'=>'温馨提示',
            'type'=>'',
            'key'=>'thing4',
        );
    }
    if ($mbinfo['name']=="砍价进度通知"){
        $form[]=array(
            'name'=>'活动名称',
            'value'=>$title,
            'key'=>'thing1',
        );
        $form[]=array(
            'name'=>'砍价进度',
            'value'=>'',
            'key'=>'thing2',
        );
        $form[]=array(
            'name'=>'温馨提示',
            'type'=>'',
            'key'=>'thing3',
        );
    }
    if ($mbinfo['name']=="新品开售提醒"){
        $form[]=array(
            'name'=>'新品名称',
            'value'=>$title,
            'key'=>'thing4',
        );
        $form[]=array(
            'name'=>'新品详情',
            'value'=>'',
            'key'=>'thing5',
        );
        $form[]=array(
            'name'=>'开售时间',
            'type'=>'daterange',
            'key'=>'date6',
        );
    }
    if ($mbinfo['name']=="预约商品开售通知"){
        $form[]=array(
            'name'=>'商品名称',
            'value'=>$title,
            'key'=>'thing2',
        );
        $form[]=array(
            'name'=>'开售时间',
            'type'=>'daterange',
            'key'=>'date1',
        );
        $form[]=array(
            'name'=>'备注',
            'value'=>'',
            'key'=>'thing3',
        );
    }
    if ($mbinfo['name']=="预售尾款支付提醒"){
        $form[]=array(
            'name'=>'商品名称',
            'value'=>$title,
            'key'=>'thing1',
        );
        $form[]=array(
            'name'=>'支付期限',
            'value'=>'',
            'key'=>'thing3',
        );
        $form[]=array(
            'name'=>'温馨提示',
            'value'=>'',
            'key'=>'thing4',
        );
    }
    if(checksubmit('submit')) {
        if ($op=='post'){
            $total =  db_fetchcolumn( 'SELECT count(*) FROM ' . tablename ( t_fans )." 
    where themeid=$themeid and info->'$.\"".$_P['template_id']."_count\"' >= 1 ");
            $sendlimit = intval($_P['sendlimit']);
            if ( $sendlimit > $total ){
                return_msg('限制发送数量不能大于当前可发送数量');
            }

            foreach ($form as $index => $item){
                if ($item['type']=='daterange'){
                    $value=$_P[$item['key']]['start']."~".$_P[$item['key']]['end'];
                }else{
                    if (empty($_P[$item['key']])){
                        return_msg($item['name']  . '必须填写才可发送');
                    }else {
                        $value = mb_substr(trim($_P[$item['key']]), 0, 20, 'utf-8');
                    }
                }
                $form[$index]['value']=$value;
            }
            $op = 'confirm';
        }
    }
    if(checksubmit('confirm')) {
        foreach ($form as $index => $item){
            $message[$item['key']]= array(
                'value'=>trim($_P[$item['key']]),
            );
        }

//        $fans = db_select ( 'SELECT * FROM ' . tablename ( t_fans )." where themeid=$themeid and info->'$.\"".$_P['template_id']."_count\"' >= 1" );
//        if (empty($fans)){
//            return_msg('没有用户订阅');
//        }else{
//            foreach ($fans as $index=>$item){
//                Util::sendMBXCX($system,$theme,$item['openid'],$_P['template_id'],$message);
//            }
//            return_msg('成功发送'.count($fans).'条');
//        }
//
        $message = urlencode(json_encode($message));
        $total =  db_fetchcolumn( 'SELECT count(*) FROM ' . tablename ( t_fans )." 
    where themeid=$themeid and info->'$.\"".$_P['template_id']."_count\"' >= 1 ");
        $sendlimit = intval($_P['sendlimit']);
        if ( $sendlimit < $total && $sendlimit!=0){
            $total = $sendlimit;
        }
        $url = createWebUrl('mbxx', array('op'=>'send','template_id'=>$_P['template_id'],'userlimit'=>$_P['userlimit'],'page'=>1,'message'=>$message,'total'=>$total));
        echo "<script language='javascript' type='text/javascript'>";
        echo "window.location.href='$url';";
        echo "</script>";
        exit;
    }
}



if ($op=='send'){
    $pageNumber = max(intval($_P['page']),1);
    $pagesize = 10 ;
    $total = intval($_P['total']);
    $message = urldecode($_P['message']);
    $message = json_decode($message,true);

    echo "第 ".$pageNumber . " 页 共 ".ceil($total /$pagesize). " 页 共 ". $total . " 条数据 <br>";


    $userlimit = $_P['userlimit'];
    $userlimit_where = '';
    switch ($userlimit){
        case 0:    //已核销的不发
               $hexiao_uid = db_select("SELECT uid FROM ".tablename(t_hexiao)." WHERE themeid=$themeid", array(), 'uid');
               if($hexiao_uid){
                      $uids =  implode(',',array_keys($hexiao_uid));
                       $userlimit_where = " and uid not in ({$uids})";
               }
            break;
        case 1:    //今日未发放
            $hexiao_uid = db_select("SELECT uid FROM ".tablename(t_mbxxlog)." WHERE themeid=$themeid and template_id='" . $_P['template_id'] . "' and sendtime>" . strtotime( date('Y-m-d 00:00')), array(), 'uid');
            if($hexiao_uid){
                $uids =  implode(',',array_keys($hexiao_uid));
                $userlimit_where = " and uid not in ({$uids})";
            }
            break;
    }


   $fans_sql = "SELECT * FROM " . tablename ( t_fans )."  where themeid=$themeid and info->'$.\"".$_P['template_id']."_count\"' >= 1 {$userlimit_where} limit " . ($pageNumber - 1) * $pagesize . "," . $pagesize;
   $fans = db_select ($fans_sql );

    if (empty($fans)){
        return_msg('没有用户订阅');
    }else{
        foreach ($fans as $index=>$item){
            $r = Util::sendMBXCX($system,$theme,$item['openid'],$_P['template_id'],$message);
            $showname = $item['username']?$item['username']:$item['nickname'];
            echo $showname . "----" .$item['mobile'] . $r['msg'] . " <br>";
        }
    }
    sleep(3);

    if ($pageNumber *$pagesize < $total) {
        $url = createWebUrl('mbxx', array('op'=>'send','template_id'=>$_P['template_id'],'userlimit'=>$_P['userlimit'],'page'=>1,'message'=>$_P['message'],'total'=>$total));
        echo "<script language='javascript' type='text/javascript'>";
        echo "window.location.href='$url';";
        echo "</script>";
    }
    exit;

}
$return_clicent = get_defined_vars();
return view('/mbxx', $return_clicent);
}
}